const { createServer } = require("http");
const { Server } = require("socket.io");

const httpServer = createServer();
const io = new Server(httpServer, { cors: true  /* options */ });
const userPool=[]
io.on("connection", (socket) => {
  // ...
  try{
    
    //登录
    socket.on("login", (arg) => {
      if(!userPool.some((item,index)=>{
        if(item.user_id==arg.user_id){
          userPool[index].fromScoketId=arg.fromScoketId||socket.id
          return true
        }
      })){
        userPool.push(arg)
      }
      io.local.emit("login",arg)
      io.local.emit('userList',userPool)
    });
    
    socket.on("to", (arg) => {
      socket.emit('leave',arg)
    });
    //发所有人的消息
    socket.on("all", (args) => {
      io.local.emit('all',args)
      
    });
    //发特定人的消息
    socket.on("sendMsg", (args) => {
      socket.to(args.toScoketId+'').emit('sendMsg',args)
      socket.emit('sendMsg',args)
      
    });
    socket.on("leave", (arg) => {
      try{
        userPool.some((item,index)=>{
          if(item.user_id==arg.user_id){
            userPool.splice(index,1)
          }
        })
        io.local.emit("leave",arg)
        
      }catch{

      }
    });
  }catch(e){
    console.log(e)
  }
  
  //错误
  // socket[Symbol.for('nodejs.rejection')] = (err) => {
  //   socket.emit("error", err);
  // };
});

httpServer.listen(3000);